package com.product.handler;


import com.product.result.ApiResult;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

//全局异常处理
@RestControllerAdvice
public class ValidatedBindException {

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseEntity<ApiResult<Map<String, String>>> handleValidationExceptions(MethodArgumentNotValidException ex) {
        Map<String, String> errors = new HashMap<>();
        ex.getBindingResult().getAllErrors().forEach(error -> {
            String fieldName = ((org.springframework.validation.FieldError) error).getField();
            String errorMessage = error.getDefaultMessage();
            errors.put(fieldName, errorMessage);
        });
        ex.printStackTrace();
        ApiResult<Map<String, String>> response = ApiResult.getResult(errors, HttpStatus.BAD_REQUEST.value(), "参数校验失败");
        return new ResponseEntity<>(response, HttpStatus.BAD_REQUEST);
    }

    @ExceptionHandler(ParameterValidationException.class)
    public ResponseEntity<ApiResult<String>> handleCustomException(ParameterValidationException ex) {
        ApiResult<String> response = ApiResult.getResult(null, ex.getStatus(), ex.getMessage());
        ex.printStackTrace();
        return new ResponseEntity<>(response, HttpStatus.valueOf(ex.getStatus()));
    }

    @ExceptionHandler(Exception.class)
    public ResponseEntity<ApiResult<String>> handleGeneralException(Exception ex) {
        ApiResult<String> response = ApiResult.getResult(null, HttpStatus.INTERNAL_SERVER_ERROR.value(), ex.getMessage());
        ex.printStackTrace();
        return new ResponseEntity<>(response, HttpStatus.INTERNAL_SERVER_ERROR);
    }
}
